package com.zztl.infiniteBand.presenter

import android.app.Activity
import android.content.Context
import com.zztl.infiniteBand.base.BasePresenter
import com.zztl.infiniteBand.model.GetVerifyBean
import com.zztl.infiniteBand.model.NoDataResponseBean
import com.zztl.infiniteBand.net.FilterSubscriber
import com.zztl.infiniteBand.net.RetorfitServiceManger
import com.zztl.infiniteBand.net.converter.DataConverter
import com.zztl.infiniteBand.net.requestBean.GetVerifyRequest
import com.zztl.infiniteBand.net.requestBean.IdentityVerifyRequest
import com.zztl.infiniteBand.ui.view.mvpview.CodeView
import com.zztl.infiniteBand.util.timer.BaseTimerTask
import com.zztl.infiniteBand.util.timer.ITimerListener
import java.util.*

/**
 * @desc
 * @auth ${user}
 * @time 2018/6/22  17:22
 */
open class BaseCodePresenter<V :CodeView> : BasePresenter<V>(), ITimerListener {
    private var mTimer: Timer? = null
    private val CountNum = 60//倒计时总数
    private var mCount: Int = 0//倒计时计算
    private var mActivity: Activity? = null

    open fun getCode(getVerifyRequest: GetVerifyRequest, context: Context) {
        addSubscribe(RetorfitServiceManger.observe(RetorfitServiceManger.instance!!.apiService.getCode(DataConverter.instance.toJson(getVerifyRequest)))
                .subscribe(object : FilterSubscriber<GetVerifyBean>(context) {
                    override fun success(bean: GetVerifyBean) {}

                    override fun fail() {
                        super.fail()
                        view!!.getCodeFail()
                    }
                }))

    }


    fun identityVerity(request: IdentityVerifyRequest, context: Context) {
        addSubscribe(RetorfitServiceManger.observe(RetorfitServiceManger.instance!!.apiService.identityVerify(DataConverter.instance.toJson(request)))
                .subscribe(object : FilterSubscriber<NoDataResponseBean>(context) {
                    override fun success(bean: NoDataResponseBean) {
                        view!!.getCodeSuccess()
                    }


                }))

    }

    fun startCountDown(activity: Activity) {
        this.mActivity = activity
        if (mTimer == null) {
            mTimer = Timer()
        }
        mCount = CountNum
        val task = BaseTimerTask(this)
        mTimer!!.schedule(task, 0, 1000)
    }

    override fun onTimer() {
        mActivity!!.runOnUiThread {
            mCount--
            view!!.setDisableView(mCount)
            if (mCount < 0) {
                view!!.setUseableView()
                destoryTimer()
            }
        }
    }

    fun resetSmsView() {
        mCount = 0
        view!!.setUseableView()
        destoryTimer()
    }


    fun destoryTimer() {
        if (null != mTimer) {
            mTimer!!.cancel()
            mTimer = null
        }
    }


}
